package com.escapeicon.bigevent.service.impl;

import com.escapeicon.bigevent.mapper.ArticleMapper;
import com.escapeicon.bigevent.pojo.dto.PageBean;
import com.escapeicon.bigevent.pojo.entity.Article;
import com.escapeicon.bigevent.service.ArticleService;
import com.escapeicon.bigevent.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        // 1. 补充属性
        Map<String, Object> map = (Map<String, Object>) ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        // 2. 保存数据
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> getArticleForPage(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 1. 新建 pageBean
        PageBean<Article> pageBean = new PageBean<>();

        // 2. 开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        // 3. 查询
        Map<String, Object> map = (Map<String, Object>) ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> articleList = articleMapper.getArticleForPage(userId,categoryId,state);

        // 4. 返回结果
        Page<Article> articles = (Page<Article>) articleList;
        pageBean.setTotal(articles.getTotal());
        pageBean.setItems(articles.getResult());

        return pageBean;
    }

    @Override
    public Article getDetail(Integer id) {
        return articleMapper.getDetail(id);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
